package Models

import (
	"gorm.io/gorm"

	"hyper/supports/database"
	"hyper/supports/models"
	"hyper/supports/password"
)

// 用户模型
type User struct {
	models.BaseModel

	UserName   string `gorm:"type:varchar(255);unique;not null;comment:用户名" json:"username,omitempty"`
	Email      string `gorm:"type:varchar(255);not null;comment:邮箱" json:"email,omitempty"`
	Password   string `gorm:"type:varchar(255);not null;comment:密码" json:"-"`
	RoleId     uint64 `gorm:"type:bigint;index;default:0;not null;comment:角色id" json:"role_id,omitempty"`
	Phone      string `gorm:"type:varchar(255);not null;comment:手机号码" json:"phone,omitempty"`
	RealName   string `gorm:"type:varchar(255);not null;comment:真实姓名" json:"real_name,omitempty"`
	IsBan      int    `gorm:"default:0;not null;comment:是否禁用：0、否；1、是" json:"is_ban,omitempty"`
	TwoFa      string `gorm:"type:varchar(255);null;comment:google 2fa认证" json:"two_fa,omitempty"`
	Avatar     string `gorm:"type:varchar(255);null;comment:用户头像" json:"avatar,omitempty"`
	Status     int    `gorm:"default:1;not null;comment:用户状态 0：禁用； 1：正常 2: 密码错误禁用" json:"status,omitempty"`
	RegisterIp string `gorm:"type:varchar(255);null;comment:注册IP" json:"register_ip,omitempty"`

	models.CommonTimestampsField
	models.DeletedAtTimestampsField
}

// 创建用户
func (u *User) Create() {
	database.DB.Create(&u)
}

// BeforeSave GORM 的模型钩子，在保存和更新模型前调用
func (user *User) BeforeSave(tx *gorm.DB) (err error) {

	if !password.IsHashed(user.Password) {
		user.Password = password.Hash(user.Password)
	}
	return
}

// 通过 用户名 / 邮箱 / 手机 来登录
func IsUserExist(obj string) (userModel User) {
	database.DB.Model(&User{}).Where("user_name = ?", obj).Or("email = ?", obj).Or("phone = ?", obj).First(&userModel)
	return
}

// ComparePassword 对比密码是否匹配
func (user *User) ComparePassword(_password string) bool {
	return password.CheckHash(_password, user.Password)
}
